﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using LB.Server.DAL.DomainEntitites;

namespace LB.Server.DAL.EntityFramework
{
    public class BookRepositoryEF : IBookRepository, IDisposable
    {
        readonly RepositoryDataContext dataContext = new RepositoryDataContext();

        #region IBookRepository

        public Book GetBook(int bookId)
        {
            return dataContext.Books.Find(bookId);
        }

        public List<Book> GetAllBooks()
        {
            var books = dataContext.Books.ToList();
            return books;
        }

        public List<Book> GetBooksByAuthor(int authorId)
        {
            var books = dataContext.Books.Where(b=>b.BookId==authorId).ToList();
            return books;
        }

        public Book AddBook(Book newBook)
        {
            var result = dataContext.Books.Add(newBook);
            dataContext.SaveChanges();
            return result;
        }

        public Chapter AddChapter(Chapter chapter)
        {
            var result = dataContext.Chapters.Add(chapter);
            dataContext.SaveChanges();
            return result;
        }

        public List<Chapter> GetChapters(int bookId)
        {
            return dataContext.Chapters.Where(c => c.BookId == bookId).ToList();
        }
        #endregion

        #region IDisposable

        protected void Dispose(bool disposing)
        {
            if (disposing)
            {
                dataContext.Dispose();
            }
            GC.SuppressFinalize(this);
        }

        public void Dispose()
        {
            Dispose(true);
        }

        #endregion
    }
}